import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';
import request from '@/utils/request';

interface GenerateDatasetModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: () => void;
  datasetId: number;
}

const GenerateDatasetModal: React.FC<GenerateDatasetModalProps> = ({
  visible,
  onCancel,
  onOk,
  datasetId,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible && datasetId) {
      const generateNameAndDescribe = async () => {
        try {
          const response = await request('/PDS/DataSetNameDescribeGenerate', {
            method: 'POST',
            data: {
              dataset_id: datasetId
            },
          });

          if (response.data.code === 200) {
            form.setFieldsValue({
              dataset_name: response.data.data.dataset_name,
              dataset_describe: response.data.data.dataset_describe,
            });
          } else {
            message.error(response.data.msg || '预生成数据集名称和描述失败');
          }
        } catch (error) {
          console.error('预生成数据集名称和描述失败:', error);
          message.error((error as Error).message || '预生成数据集名称和描述失败');
        }
      };

      generateNameAndDescribe();
    }
  }, [visible, datasetId, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      const response = await request('/PDS/DataSetGenerate', {
        method: 'POST',
        data: {
          dataset_id: datasetId,
          dataset_name: values.dataset_name,
          dataset_describe: values.dataset_describe,
        },
      });

      if (response.data.code === 200) {
        message.success('数据集生成成功');
        form.resetFields();
        onOk();
      } else {
        message.error(response.data.msg || '数据集生成失败');
      }
    } catch (error) {
      console.error('生成数据集失败:', error);
      message.error('生成数据集失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="生成数据集"
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      confirmLoading={loading}
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Form.Item
          name="dataset_name"
          label="数据集名称"
          rules={[{ required: true, message: '请输入数据集名称' }]}
        >
          <Input placeholder="请输入数据集名称" />
        </Form.Item>
        <Form.Item
          name="dataset_describe"
          label="数据集描述"
          rules={[{ required: true, message: '请输入数据集描述' }]}
        >
          <Input.TextArea placeholder="请输入数据集描述" rows={4} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default GenerateDatasetModal; 